package com.oauth.service.members.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.oauth.logging.OAuthLogger;
import com.oauth.service.members.beans.Member;
import com.oauth.service.members.dao.MemberDAO;

@Service
public class MemberServiceImpl implements MemberService {

	@Autowired
	private MemberDAO mMemberDAO;
	private static final long ONE_DAY = 86400000;
	private OAuthLogger logger = OAuthLogger.getLogger(this.getClass());

	/**
	 * @param pMemberDAO
	 *            the memberDAO to set
	 */
	public void setMemberDAO(MemberDAO pMemberDAO) {
		mMemberDAO = pMemberDAO;
	}

	/**
	 * @param interval
	 * @return
	 * @see com.oauth.service.members.dao.MemberDAO#getNewUsers(int)
	 */
	@Override
	public List<String> getNewUsers(int interval) {
		return mMemberDAO.getNewUsers(interval);
	}

	@Override
	public void deleteMember(Long memberId) {
		Member member = mMemberDAO.getMember(memberId);
		if (member != null) {
			mMemberDAO.deleteMember(member);
		}
	}

	public Member getMember(Long memberId) {
		return mMemberDAO.getMember(memberId);
	}

	public boolean updateMember(Member member) {
		return mMemberDAO.updateMember(member);
	}

	public Member getMember(String pEmailId) {
		return mMemberDAO.getMember(pEmailId);
	}

	public Long getCount() {
		return mMemberDAO.getCount();
	}

	public Member getMember(String pEmailId, boolean pAutoCreate) throws Exception {
		Member member = mMemberDAO.getMember(pEmailId);
		if (member == null && pAutoCreate) {
			Member newMember = new Member();
			newMember.setEmail(pEmailId);
			member = mMemberDAO.addMember(newMember);
		} else {
			updateLastLoginDate(member);
		}
		return member;
	}

	private void updateLastLoginDate(Member member) {
		try {
			long prevTime = member.getLastLogin().getTime();
			long currentTime = new Date().getTime();
			if ((currentTime - prevTime) > ONE_DAY) {
				member.setLastLogin(new Date());
				updateMember(member);
			}
		} catch (Exception e) {
			logger.error("Error updating last login date for member=" + member.getMemberId());
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.oauth.service.members.service.MemberService#getActiveUsers(int)
	 */
	@Override
	public List<String> getActiveUsers(int interval) {
		return mMemberDAO.getActiveUsers(interval);
	}
}
